package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;

@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {

        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2.组装成父子的树形结构

        //2.1)、找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu)->{
            //menu是由entities流过滤之后传过来的元素（CategoryEntity）对象，相当于迭代entities集合中的元素
            menu.setChildren(getChildren(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            //sorted方法传入的是比较器对象的compare方法，menu1\2依然是迭代集合中的对象
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {

        //TODO 1、检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);

    }

    @Override
    public Long[] getAttrGroupIdPath(AttrGroupEntity attrGroup) {

        List<Long> groupIdList = new ArrayList<>();
        CategoryEntity categoryEntity = this.getById(attrGroup.getCatelogId());
        groupIdList.add(categoryEntity.getCatId());

        while(categoryEntity.getParentCid() != 0){
            groupIdList.add(categoryEntity.getParentCid());
            categoryEntity = this.getById(categoryEntity.getParentCid());
        }
        log.info(groupIdList.toString());
        int count = groupIdList.size();
        Long[] groupIds = new Long[count];
        for (int i = 0; i < groupIdList.size(); i++){
            groupIds[i] = groupIdList.get(count - 1);
            count--;
        }
        log.info(Arrays.toString(groupIds));
        return groupIds;
    }

    /**
     *
     * @param root 为一级目录
     * @param all  表中所有数据
     * @return   返回子目录集合
     */
    private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            //找到当前根目录的子目录
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
            //再以当前子目录作为根目录递归寻找其子目录
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //2.菜单的排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}